#include "dialog_datatrans.h"
#include "ui_dialog_datatrans.h"
#include "pub_var.h"
#include "QPushButton"
#include <QDebug>
#include <QDate>
#include <QMessageBox>
#include <QRegExp>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QTimer>
#include <QFile>

//  QByteArray ret = pub::decode(ui->teFields->toPlainText().toLatin1(), ui->leConstrain->text().toLatin1()).toLatin1();
//ui->teResult->insertPlainText( QString::fromUtf8(ret) );
//    QByteArray contu = ui->teFields->toPlainText().toUtf8();
//    ui->teResult->insertPlainText(pub::encode(contu , ui->leConstrain->text().toLatin1()));


/*
    // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    QString strMacAddr = "";
    for(int i = 0; i < nCnt; i ++)
    {

        if(nets[i].flags().testFlag(QNetworkInterface::IsUp)
                && nets[i].flags().testFlag(QNetworkInterface::IsRunning)
                && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }
    qDebug()<< strMacAddr;
*/
Dialog_datatrans::Dialog_datatrans(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_datatrans)
{
    ui->setupUi(this);
    qro = new QSqlQuery(pub::db_o);
    qrm = new QSqlQuery(pub::db_m);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/trans").toRect();
    this->setGeometry(rct);

    connect(ui->pbExit,SIGNAL(pressed()),this,SLOT(pbExitPressed()));
    connect(ui->pbRun, &QPushButton::clicked, this, &Dialog_datatrans::pbRunPressed);
    connect(ui->pbShowFields,&QPushButton::clicked,this,&Dialog_datatrans::pbShowFieldsPressed);
    connect(this,SIGNAL(rejected()),this,SLOT(windClose()));


//    //初始化医保线程
//    qDebug()<<"initialYb";
//    ybBusiness = new ThreadYb(this);
//    ybBusiness->moveToThread(&thread);
//    qDebug()<<"start";
//    thread.start();
//    connect(this, SIGNAL(opThread(int, QString)), ybBusiness, SLOT(doWork(int, QString)));

/*
 *
 * create or replace trigger trig_drug_base_recal
  after insert on drug_sub_account
  for each row
declare
  -- local variables here
  --  recal_sum int;
begin

  UPDATE DRUG_BASE_INFO d SET d.recal = d.recal + :new.oper_sum WHERE d.drug_code = :new.drug_code;

end trig_drug_base_recal;





create or replace trigger trig_drug_base_dup
  before insert on drug_sub_account
  for each row

declare
  recal_sum int;
  drug_c char(50);
  cursor cur is select drug_code from drug_sub_account
         where drug_code = :new.drug_code and  oper_date = :new.oper_date
           and atinc = :new.atinc and oper_name = :new.oper_name and oper_sum = :new.oper_sum;

begin

  open cur;
  fetch cur into drug_c;

  if(cur%found) then
     --if recorder has been inserted , set operate number to 0
    :new.oper_sum := 0;
--     UPDATE DRUG_BASE_INFO d  SET d.recal = d.recal - :new.oper_sum WHERE d.drug_code = :new.drug_code;
  end if;
  close cur;

  --read value after calculate
  select recal into recal_sum from drug_base_info WHERE drug_code = :new.drug_code;

  recal_sum := recal_sum + :new.oper_sum;

  --补偿之后挂账数量为 0 ，设置挂账已平衡标志。
  if( recal_sum = 0) then
    :new.balanced := '1' ;
  end if;

end trig_drug_base_dup;
*/


}

Dialog_datatrans::~Dialog_datatrans()
{
    delete ui;
}



void Dialog_datatrans::pbRunPressed()
{


    ui->teResult->clear();
    ui->teFields->clear();

    QByteArray bt;

    //QFile f(ui->leTableName->text());//"d:/0down/test.txt"
    //if(!f.open(QIODevice::ReadOnly)){
     //   QMessageBox::information(this,"note","open file failed.");
     //   return;
   // }
    //bt = f.readAll();
    //f.close();

//ui->teFields->insertPlainText("\r\nsource bt : "+bt);

    int len = bt.length();

    QString btStr = QString::fromLatin1(bt.toBase64(),len);

QJsonValue btS0 = btStr;

//ui->teFields->insertPlainText("\r\nQString btStr : " + btStr);
//ui->teFields->insertPlainText("\r\nJsonString btS0 : " + btS0.toString());

    QJsonObject in;
    QJsonObject inpu,inpud;
    QJsonDocument d;

    QString inp;
    //QString msgid;  //发送方报文ID ,定点医药机构编号(12)+时间(14)+顺序号(4)  时间格式：yyyyMMddHHmmss
    inp = pub::getYbStrJ("9160","");   //
    if(inp.isEmpty()){
        //pub::useInsurance = false;  //设置医保不可用
        QMessageBox::information(this,"note","申请交易流水号失败！");
        return; //未能成功申请交易流水号
    }


    in.insert("infno", "9160");
    in.insert( "msgid", inp);
    in.insert("mdtrtarea_admvs", "210100");
    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    //in.insert("cainfo","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);


    //inpu.insert("in",  btS0);//文件数据

    //in//pu.insert("filename", "test9101"+QDateTime::currentDateTime().toString("yyyyMMddhh24mmss")+".txt");//文件名
    //inpu.insert("fixmedins_code", pub::hos_ybbh);//定点医药机构

    inpu.insert("businesstype","1");//
    inpu.insert("psnno", pub::getStr(ui->leConstrain->text(),"^",1));//
    inpu.insert("setlid", pub::getStr(ui->leConstrain->text(),"^",2));//

//    inpud.insert("fsUploadIn",inpu);
                inpud.insert("data",inpu);
    in.insert("input", inpud);
qDebug()<<"9160 in "<<in;
    QJsonDocument indoc ;
    indoc.setObject(in);



    QNetworkRequest request;



    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, ui->comboBox->currentText());
    //QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    QNetworkAccessManager naManager ;//= new QNetworkAccessManager(this);

qDebug()<<"indoc is : "<<indoc;
    QNetworkReply* reply = naManager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。


    qDebug()<<" request 9101 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray btret = reply->readAll();
    qDebug()<<btret;
ui->teResult->insertPlainText("\r\n9102 return value : " + btret);
    QString t = QString::fromLocal8Bit(btret);

    QJsonParseError json_error;

    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

        return ;
    }



ui->teResult->insertPlainText("\r\n9101 outDoc " + jsdc.toJson());
    QJsonObject jsob = jsdc.object();
qDebug()<< "9102 outObject "<<jsob;

QJsonObject  ret9101 = jsob.value("output").toObject();

QString rt = ret9101.value("setl_print").toString();

QByteArray rtbt = QByteArray::fromBase64( rt.toLatin1());



QFile ff("d:/0down/z" + QDateTime::currentDateTime().toString("yyyyMMddHHmmss") +  ".pdf");
if(!ff.open(QIODevice::WriteOnly)){
    QMessageBox::information(this,"note","create file failed.");
    return;
}
ff.write(rtbt);
ff.close();



return;

QJsonObject::iterator it;
it = ret9101.begin();
while(it != ret9101.end()){

    QString k = it.key();
    QString v = it.value().toString();
    ui->teResult->insertPlainText("\r\n"+k+" : "+v);

    it ++;
}


//qDebug()<<ret9101.value("file_qury_no").toString();
























    return;
//      QByteArray ret = pub::decode(ui->teFields->toPlainText().toLatin1(), ui->leConstrain->text().toLatin1()).toLatin1();
//    ui->teResult->insertPlainText( QString::fromUtf8(ret) );


}

void Dialog_datatrans::pbExitPressed()
{


    ui->teResult->clear();
    ui->teFields->clear();

    QByteArray bt0, bt1;

    QFile f("d:/0down/test.txt");//"d:/0down/test.txt"
    if(!f.open(QIODevice::ReadOnly)){
       QMessageBox::information(this,"note","open file failed.");
       return;
    }
    bt0 = f.readAll();
    bt1 = f.readAll();
    f.close();

//ui->teFields->insertPlainText("\r\nsource bt : "+bt);

    int len0 = bt0.length();
    int len1 = bt1.length();

    QString btStr1 = QString::fromLatin1(bt1,len0);
    QString btStr0 = QString::fromLatin1(bt0.toBase64(),len0);
    //QString btStr1 = QString::fromLatin1(bt1,len1);
QJsonValue btS0 = btStr0;
QJsonValue btS1 = btStr1;
qDebug()<<btS0;
qDebug()<<btS1;
    QJsonObject in;
    QJsonObject inpu,inpud;
    QJsonDocument d;

    QString inp;
    //QString msgid;  //发送方报文ID ,定点医药机构编号(12)+时间(14)+顺序号(4)  时间格式：yyyyMMddHHmmss



    in.insert("infno", "test");

    inpu.insert("inD0", btS0);
    inpu.insert("inD1", btS1);

    inpu.insert("businesstype","1");//

    inpud.insert("data",inpu);
    in.insert("input", inpud);
qDebug()<<"9160 in "<<in;
    QJsonDocument indoc ;
    indoc.setObject(in);



    QNetworkRequest request;



    //request.setUrl(QUrl(pub::hos_ybjy));
    request.setUrl(QUrl("http://192.168.1.108:9999"));

    request.setHeader(QNetworkRequest::ContentTypeHeader, ui->comboBox->currentText());
    //QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    QNetworkAccessManager naManager ;//= new QNetworkAccessManager(this);

qDebug()<<"indoc is : "<<indoc;
    QNetworkReply* reply = naManager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。


    qDebug()<<" request 9101 is returned";



    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray btret = reply->readAll();
    qDebug()<<btret;

ui->teResult->insertPlainText("\r\n9102 return value : " + btret);
    //QString t = QString::fromLocal8Bit(btret);
QString t = QString::fromUtf8(btret);

    QJsonParseError json_error;

    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","信息解析错误 " + json_error.errorString());

        return ;
    }



}
void Dialog_datatrans::postRequestFinished(QNetworkReply * rpl)
{

    QVariant statusCode = rpl->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return;
    }

    QNetworkReply::NetworkError err = rpl->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",rpl->errorString());

        return;
    }else{
        QByteArray bt = rpl->readAll();
        QString t = QString::fromLocal8Bit(bt);
//qDebug()<<"outDoc"<<t;
//ui->teResult->insertPlainText(t);
        QJsonParseError json_error;
        QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);

        ui->teResult->insertPlainText(jsdc.toJson());

        if(json_error.error != 0 ){
            QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

            return;
        }
        QJsonObject jsob = jsdc.object();

        if(jsob.value("infcode").toInt() != 0){
            QString t = jsob.value("err_msg").toString();
            QMessageBox::warning(NULL,"注意","交易失败:" + t );
        }





//        httpFinished = true;
        return;
    }

}


void Dialog_datatrans::getRequestFinished(QNetworkReply *)
{

}




void Dialog_datatrans::pbShowFieldsPressed()
{
     ui->teResult->clear();
     ui->teFields->clear();

    QString   inp = pub::getYbStrJ("9102","");   //
    if(inp.isEmpty()){
        //pub::useInsurance = false;  //设置医保不可用
        QMessageBox::information(this,"note","申请交易流水号失败！");
        return; //未能成功申请交易流水号
    }

    QJsonObject in;
    in.insert("infno", "9102");
    in.insert( "msgid", inp);
    in.insert("mdtrtarea_admvs", "210100");
    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

    QJsonObject inpu,inpud;

    inpu.insert("file_qury_no", pub::getStr(ui->leConstrain->text(),"^",1));
    inpu.insert("filename", pub::getStr(ui->leConstrain->text(),"^",2));   //
    inpu.insert("fixmedins_code", pub::hos_ybbh);   //

    inpud.insert("fsDownloadIn",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
    QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    connect(naManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(postRequestFinished2(QNetworkReply*)));
    qDebug()<< "9102 入参:" <<indoc;





    QNetworkRequest request;
    QNetworkAccessManager* naanager = new QNetworkAccessManager(this);
    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

qDebug()<<"indoc is : "<<indoc;
    QNetworkReply* reply = naanager->post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。


    qDebug()<<" request 9102 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray btret = reply->readAll();






    QFile ff("d:/0down/z" + QDateTime::currentDateTime().toString("yyyyMMddHHmmss") +  ".zip");
    if(!ff.open(QIODevice::WriteOnly)){
        QMessageBox::information(this,"note","create file failed.");
        return;
    }
    ff.write(btret);
    ff.close();





ui->teResult->insertPlainText("\r\n9102 return value : " + btret);
    QString t = QString::fromLocal8Bit(btret);


    qDebug()<<"----------------------------------";
        qDebug()<<btret;
    qDebug()<<t;
    qDebug()<<QString::fromLatin1(btret);
    qDebug()<<QString::fromUtf8(btret);
    qDebug()<<"----------------------------------";



    QJsonParseError json_error;

    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

        return ;
    }
ui->teResult->insertPlainText("\r\n9102 outDoc " + jsdc.toJson());
    QJsonObject jsob = jsdc.object();
qDebug()<< "9102 outObject "<<jsob;

QJsonObject  ret9102 = jsob.value("output").toObject();

QJsonObject::iterator it;
it = ret9102.begin();
while(it != ret9102.end()){

    QString k = it.key();
    QString v = it.value().toString();
    ui->teResult->insertPlainText("\r\n"+k+" : "+v);

    it ++;
}




    return;
    ui->teResult->clear();
    ui->leConstrain->setText("开始执行医保交易。。。");

    //QString msgid;  //发送方报文ID ,定点医药机构编号(12)+时间(14)+顺序号(4)  时间格式：yyyyMMddHHmmss
    inp = pub::getYbStrJ("1318","");   //
    if(inp.isEmpty()){
        pub::useInsurance = false;  //设置医保不可用
        QMessageBox::information(this,"note","申请交易流水号失败！");
        return; //未能成功申请交易流水号
    }

    //QJsonObject in;
    in.insert("infno", "1312");
    in.insert( "msgid", inp);
    in.insert("mdtrtarea_admvs", "210100");
    in.insert("insuplc_admdvs","");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo","");
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

    //QJsonObject inpu,inpud;
    inpu.insert("updt_time", "2021-08-01 00:00:00");   //更新时间
    inpu.insert("page_num", 1);    //当前页数
    inpu.insert("page_size", 10);   //本页数据量

    inpud.insert("data",inpu);
    in.insert("input", inpud);



    return;
/*
    sq = "select column_name,data_type from information_schema.columns where table_name = '";
    sq = sq + ui->leTableName->text().trimmed()+"'";
    qrm->exec(sq);
    if(qrm->size() == 0){
        ui->teResult->setText("表名不存在！");
    }else{
        fieldsName = "";
        fieldsType = "";
        while(qrm->next()){
            fieldsName = fieldsName + qrm->value(0).toString()+",";
            fieldsType = fieldsType + qrm->value(1).toString()+",";
        }
        ui->teResult->setText(fieldsName);
    }
*/
}

void Dialog_datatrans::windClose()
{
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/trans", QVariant(this->geometry()));

}


void Dialog_datatrans::handleRet(const int r, const QString o)
{
    disconnect(ybBusiness, SIGNAL(resultReady(int, QString)), this, SLOT(handleRet(int, QString)));
    businessRetVal = r;
    businessRetStr = o;
    businessFinish = true;
}
